package kit.docker.web;

import com.jfinal.json.Json;
import com.jfinal.kit.StrKit;

import java.util.HashMap;

/**
 * API响应结果对象封装
 */
public class APIResponse extends HashMap {

    // 响应对象节点
    private static final String STATUS = "status";
    private static final String MESSAGE = "message";
    private static final String DATA = "data";

    public APIResponse() {
    }

    public static APIResponse create() {
        return new APIResponse();
    }

    public APIResponse set(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public String toJson() {
        return Json.getJson().toJson(this);
    }

    // =========================    success   ================

    public static APIResponse success() {
        return success(null, null);
    }

    public static APIResponse success(Object data) {
        return success(data, null);
    }

    public static APIResponse success(Object data, String message) {
        return APIResponse.create()
                .set(STATUS, APIResCode.SUCCESS)
                .set(MESSAGE, StrKit.isBlank(message) ? APIResCode.resCodeMap.get(APIResCode.SUCCESS) : message)
                .set(DATA, data);
    }

    // =========================    fail    =====================

    public static APIResponse fail() {
        return fail(null, null, null);
    }

    public static APIResponse failData(Object data) {
        return fail(null, data, null);
    }

    public static APIResponse failData(Integer status, Object data) {
        return fail(status, data, null);
    }

    public static APIResponse failData(String message, Object data) {
        return fail(null, data, message);
    }

    public static APIResponse failStatus(Integer status) {
        return fail(status, null, null);
    }

    public static APIResponse failStatus(Integer status, String message) {
        return fail(status, null, message);
    }

    public static APIResponse failMessage(String message) {
        return fail(null, null, message);
    }

    public static APIResponse failMessage(Integer status, String message) {
        return fail(status, null, message);
    }

    public static APIResponse failMessage(String message, Object data) {
        return fail(null, data, message);
    }

    public static APIResponse fail(Integer status, Object data, String message) {
        return APIResponse.create()
                .set(STATUS, StrKit.notNull(status) ? status : APIResCode.FAIL)
                .set(MESSAGE, StrKit.isBlank(message) ? (StrKit.notNull(status) ? APIResCode.resCodeMap.get(status) : APIResCode.resCodeMap.get(APIResCode.FAIL)) : message)
                .set(DATA, data);
    }


}
